package DBLayer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import ModelLayer.Supplier;
import ModelLayer.Person;

public class DBSupplier 
{
	private Connection con;
    private PreparedStatement pStmtSelect;
    /** Creates a new instance of DBSupplier */
    public DBSupplier()
    {
    	con = DBConnection.getInstance().getDBcon();
    }
	   private Person buildSupplier(ResultSet results)
	    {
	    	Person supp = new Supplier();
	       
	         try
	         {
	        	 supp.setId(results.getInt("id_"));
	        	 supp.setName(results.getString("name"));
	        	 supp.setAddress(results.getString("address"));
	        	 supp.setPhoneNo(results.getInt("phoneNo"));
	        	 supp.setEmail(results.getString("email"));
	        	 supp.setCountry(results.getString("country"));
	        	 supp.setcvrNr(results.getString("cvrNr"));
	             supp.setComment(results.getString("comment"));  
	               
	               
	               
	         }
	         catch(Exception e)
	         {
	             System.out.println("der skete en fejl");
	         }
	        
	        return supp;
	        
	        
	    }
	   
	   //finder en supplier.
	   public Person findSupplier(int id, boolean retriveAssociation)
       {
		  
			String wClause = "  id_ = '" +id + "'";
			return singleWhere(wClause, retriveAssociation);
       }
	
	 //singlewhere is used when only one supplier object is to be build
	  private Person singleWhere(String wClause, boolean retrieveAssociation) {
			ResultSet results;
			Person supp = new Supplier();

			String query = buildQuery(wClause);
			System.out.println(query);
			try { // read the supplier from the database
				Statement stmt = con.createStatement();
				stmt.setQueryTimeout(5);
				results = stmt.executeQuery(query);

				if (results.next()) {
					
					supp = buildSupplier(results);
					// assocaition is to be build
					stmt.close();


					
				} 
				else 
				{ // no supplier was found
					supp = null;
				}
			}// end try
			catch (Exception e) 
			{
				System.out.println("Query exception: " + e);
			}
			return supp;
		}
	  //bygger en query, som kan sendes til sql.
	  private String buildQuery(String wClause) 
	  {
			String query = "SELECT id_, name, address, phoneNo, Email, country, cvrNr, comment, zipcode FROM Supplier";
	        if (wClause.length() > 0)
	        {
				query = query + " WHERE " + wClause;
	        }
	        return query;
	  }


}
